package com.example.graduation.controller.pdf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.graduation.entity.pojo.Image;
import com.example.graduation.service.ImageService;
import com.example.graduation.util.FileUtil;
import com.example.graduation.util.PdfUtil;
import com.example.graduation.util.ShiroUtil;
import com.example.graduation.util.TimeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author Jeffery
 * Pdf权限
 */
@RequestMapping("/pdf")
@Controller
@Slf4j(topic = "PdfController")
@Api(tags = "带有pdf路径的controller")
public class PdfController {
    private static final int FILE_IO_LEN = 1024;
    private static final int DEFAULT_PAGE_SIZE = 10;

    @Resource
    private ImageService imageService;
    @Resource
    private FileUtil fileUtil;

    /**
     * 新增PDF
     *
     * @param json json参数
     * @return boolean
     */
    @PostMapping("/insertPdf")
    @ResponseBody
    @ApiOperation("新增PDF")
    public boolean insertPdf(@RequestBody JSONObject json) {
        log.info("传递的JSON数据为： {}", json);
        boolean result = true;
        Map<String, Object> paramMap = new HashMap<>(16);

        paramMap.put("image_exc", "pdf");
        String pdfId = null;
        try {
            pdfId = PdfUtil.createPDF(getParamsMap(json));
            log.info("生成的PDF ID为：{}", pdfId);
            /*
             * 将生成的PDF转为二进制文件，存储至数据库中
             */
            byte[] bytes = fileUtil.fileToByte(new File(pdfId));
            Image image = new Image();

            image.setId(pdfId);
            image.setUId(ShiroUtil.getUserId());
            image.setCreateTime(TimeUtil.getCurrentTimeStamp());
            image.setVersion(1);
            image.setIsDeleted(0);
            image.setExc("pdf");
            image.setBlog(bytes);

            imageService.save(image);
            log.info("PDF生成成功！返回的文件ID为：{}", pdfId);
        } catch (IOException e) {
            log.error("发生异常了！:{}", e.getMessage());
            result = false;
        }
        return result;
    }

    public Map<String, Object> getParamsMap(JSONObject json) {
        Map<String, Object> resultMap = new HashMap<>(16);

        resultMap.put("name", json.getString("name"));
        resultMap.put("address", json.getString("address"));
        resultMap.put("phone", json.getString("phone"));
        resultMap.put("attend", json.getString("attend"));
        resultMap.put("identity", json.getString("identity"));
        resultMap.put("education", json.getString("education"));
        resultMap.put("education_experience", json.getString("education_experience"));
        resultMap.put("honor", json.getString("honor"));
        resultMap.put("company", json.getString("company"));
        resultMap.put("salary", json.getString("salary"));

        return resultMap;
    }

    /**
     * 获取pdf的接口
     *
     * @param pdfId id
     */
    @GetMapping("/getPdfById")
    @ResponseBody
    @ApiOperation("获取pdf")
    @ApiImplicitParam(name = "pdfId", value = "pdfId")
    public void getPdfById(@RequestParam("pdfId") String pdfId, HttpServletResponse response) {
        String userId = ShiroUtil.getUserId();
        QueryWrapper<Image> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("image_id", pdfId);
        Image image = imageService.getOne(wrapper);

        //IO流读取文件
        response.setContentType("application/pdf");
        response.setCharacterEncoding("UTF-8");
        byte[] bytes = image.getBlog();
        OutputStream outputStream;
        InputStream in;
        try {
            outputStream = response.getOutputStream();
            in = new ByteArrayInputStream(bytes);
            int len;
            byte[] buf = new byte[0];
            try {
                buf = new byte[1024];
            } catch (Exception e) {
                e.printStackTrace();
            }
            while ((len = in.read(buf, 0, FILE_IO_LEN)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();
            log.info("文件读取完毕");
        } catch (Exception e) {
            log.error("发生异常了：" + e.getMessage());
        }
    }

    /**
     * 分页获取PDF
     *
     * @param pageNumber 当前页数
     * @return json字符串
     */
    @GetMapping("/getAllPdfs/{pageNumber}")
    @ResponseBody
    @ApiOperation("分页获取PDF")
    @ApiImplicitParam(name = "pageNumber", value = "当前页数", defaultValue = "1")
    public String getAllPdfs(@PathVariable("pageNumber") Integer pageNumber) {
        PageHelper.startPage(pageNumber, DEFAULT_PAGE_SIZE);
        //此处应该给所有文件  增加一个标识字段   表明当前文件是什么  否则无法进行区分pdf  jpg excel
        QueryWrapper<Image> wrapper = new QueryWrapper<>();
        wrapper.eq("image_exc", "pdf");
        List<Image> list = imageService.list(wrapper);

        PageInfo<Image> pageInfo = new PageInfo<>(list);
        String result = JSON.toJSONString(pageInfo);
        log.info("返回JSON为 ： {}", result);
        return "";
    }
}
